package kr.hkit.powerjava.chapter24;

import java.util.*;

public class ServiceStudent {
	//1. 시작(StudentDao 객체 생성후, load())
	//2. 메뉴보이기(prnMenu)
	//3. 종료(StudentDao.save())
	
	private StudentDao dao;
	private Scanner sc;
	
	public ServiceStudent(){
		dao = new StudentDao();
		sc = new Scanner(System.in);
		init();
		
	}
	
	public ServiceStudent(StudentDao dao) {
		this.dao = dao;
		sc = new Scanner(System.in);
		init();
	}

	private void init() {
		dao.loadFile();
		prnMenu();
	}

	private void prnMenu() {

		Student std = null;
		int res = 0;
		do{
			System.out.print("1.입력\n2.삭제\n3.수정\n4.검색\n5.리스트보기\n6.종료");
			res = sc.nextInt();
		switch(res){
			case 1:
				//학생정보입력
				std = inputStdInfo(true); //학번, 성명, 국,영,수
				dao.insertItem(std);
				break;
			case 2:
				//삭제, 리스트를 보여주고 번호를 입력받음
				dao.prnItemList(null);
				System.out.print("삭제할 학생정보를 입력하시오");
				std = inputStdInfo(false);
				dao.deleteItem(std);
				break;
			case 3:
				//수정, 리스트를 보여주고 수정할 학생정보를 입력받음
				dao.prnItemList(null);				
				std = inputStdInfo(true);
				dao.updateItem(std);
				break;
			case 4:
				//검색
				std = inputStdInfo(false); //학번, 성명
				try{
				std = dao.searchItem(std);
				}catch(ArrayIndexOutOfBoundsException e){
					System.out.println("학생 정보 없음");
				}
				break;
			case 5:
				prnSubMenu();
				break;
			case 6:
				dao.saveFile();
				sc.close();
				System.exit(0);
				break;
			default:
				res = 6;
		}
		}while(res<6);
	}

	private Student inputStdInfo(boolean gubun) {
		System.out.println("학번 성명");
		int num = sc.nextInt();
		String name = sc.next();
		
		if(gubun){
			System.out.println("국어 영어 수학 ");
			int kor = sc.nextInt();
			int eng = sc.nextInt();
			int math = sc.nextInt();
			return new Student(num, name, kor, eng, math);
		}else{
			return new Student(num,name);
		}
		
	}

	private void prnSubMenu() {
		System.out.print("1. 이름순 정렬 2. 성적순 정렬 3. 번호순 정렬");
		int res = sc.nextInt();
		switch(res){
			case 1:
				dao.prnItemList(new Comparator<Student>() {
					
					@Override
					public int compare(Student o1, Student o2) {
						return o1.getStdName().hashCode()-o2.getStdName().hashCode();
					}
				});
				break;
			case 2:
				dao.prnItemList(new Comparator<Student>() {
					
					@Override
					public int compare(Student o1, Student o2) {
						return o1.totalScore()-o2.totalScore();
					}
				});
				break;
			case 3:
				dao.prnItemList(null);
				break;
			default:
				dao.prnItemList(null);
		}
	}
	
	
}
